package example.app;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Xml;

public class CRssParsTask extends AsyncTask<String, Integer, CRssListAdapter> {
	private RSSLeader mActivity;
	private CRssListAdapter mAdapter;
	private ProgressDialog mProgressDialog;
	
	//
	public CRssParsTask(RSSLeader aActivity, CRssListAdapter aAdapter) {
		mActivity = aActivity;
		mAdapter = aAdapter;
	}
	
	@Override
	protected void onPreExecute() {
		mProgressDialog = new ProgressDialog(mActivity);
		mProgressDialog.setMessage("Now Loading...");
		mProgressDialog.show();
	}
	
	//
	@Override
	protected CRssListAdapter doInBackground(String... aParams) {
		CRssListAdapter result = null;
		try {
			URL url = new URL(aParams[0]);
			InputStream is = url.openConnection().getInputStream();
			result = ParseXml(is);
		} catch(Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	//
	@Override
	protected void onPostExecute(CRssListAdapter aResult) {
		mProgressDialog.dismiss();
		mActivity.setListAdapter(aResult);
	}
	
	//
	public CRssListAdapter ParseXml(InputStream aInputStream ) throws IOException, XmlPullParserException {
		XmlPullParser parser = Xml.newPullParser();
		
		try {
			parser.setInput(aInputStream,null);
			int eventType = parser.getEventType();
			CItem currentItem = null;
			
			while(eventType != XmlPullParser.END_DOCUMENT) {
				String tag = null;
				switch(eventType) {
					case XmlPullParser.START_TAG: {
						tag = parser.getName();
						if(tag.equals("item")) {
							currentItem = new CItem();
						} else if(currentItem != null) {
							if(tag.equals("title")) {
								currentItem.SetTitle(parser.nextText());
							} else if(tag.equals("description")) {
								currentItem.SetDescription(parser.nextText());
							} else if(tag.equals("link")) {
								currentItem.SetUrl(parser.nextText());
							}
						}
					}break;
					case XmlPullParser.END_TAG: {
						tag = parser.getName();
						if(tag.equals("item")) {
							mAdapter.add(currentItem);
						}
					}break;
				}
				eventType = parser.next();
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		return mAdapter;
	}
}
